package com.ronan.imserver.processor;

import com.ronan.common.constant.Constants;
import com.ronan.common.proto.Login;
import com.ronan.common.utils.SessionManager;
import com.ronan.imserver.config.ApplicationConfig;
import com.ronan.imserver.service.RedisService;
import com.ronan.imserver.utils.SpringBeanFactory;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * FileName    : com.ronan.imserver.processor
 * Description :
 *
 * @author : ronan
 * @version : 1.0
 * Create Date : 2021/2/26 11:05
 **/
@Slf4j
public class LoginProcessor implements RIMProcessor<Login> {

    @Override
    public void process(Login login, Channel channel) {

        RedisService redisService = SpringBeanFactory.getBean(RedisService.class);
        ApplicationConfig config = SpringBeanFactory.getBean(ApplicationConfig.class);

        String accid = login.getAccid();
        String token = login.getToken();

        // step1.判断redis中是否有当前登录用户的信息
        String cacheToken = (String) redisService.get(Constants.ACCOUNT_PREFIX+accid);
        Boolean isMember = redisService.sIsMember(Constants.LOGIN_STATUS_PREFIX, accid);
        if (cacheToken == null || !cacheToken.equals(token) || !isMember) {
            // 不存在则关闭通道
            log.info("客户端:{},accid或者token错误,请重新连接!",channel.remoteAddress());
            channel.close();
        } else {
            // 保存用户与channel的关系映射
            SessionManager.put(accid, channel);
            SessionManager.saveSession(accid, token);
            log.info("当前服务IP:{}", channel.localAddress());
            InetSocketAddress inetAddress = (InetSocketAddress) channel.localAddress();
            String serverIp = inetAddress.getAddress().getHostAddress();
            String route = serverIp + ":" + config.getPort();
            log.info("当前服务route:{}", route);
            redisService.set(Constants.ROUTE_PREFIX + accid, route);
            log.info("用户[{}]登录成功!!", accid);
            log.info("用户:[{}],channel:[{}]", accid, SessionManager.get(accid));
        }
    }
}
